package lintulaskenta.pulautin;



import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class TietokannanKasittelija {

    
    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("LintulaskentaPU");

    public EntityManagerFactory getEmf() {
        return emf;
    }
    
    public void addEntity(Object entity) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(entity);
        em.getTransaction().commit();
    }

    public void removeTable(String entityName) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.createQuery("DELETE FROM " + entityName).executeUpdate();
        em.getTransaction().commit();
    }

    public List getTable(String entityName) {
        EntityManager em = emf.createEntityManager();
        return em.createQuery("SELECT e FROM " + entityName + " e").getResultList();
    }

    public Object getEntity(Class entityName, long id) {
        EntityManager em = emf.createEntityManager();
        return em.find(entityName, id);
    }

    public void execute(String query) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.createQuery(query).executeUpdate();
        em.getTransaction().commit();
    }

//    public List getResultList(String query) {
//        EntityManager em = emf.createEntityManager();
//        return em.createQuery(query).getResultList();
//    }

    public List getResultList(String query, Class luokka) {
        EntityManager em = emf.createEntityManager();
        return (List) em.createQuery(query, luokka).getResultList();
    }

    public void removeEntity(Class luokka, long id) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        Object e = em.find(luokka, id);
        em.remove(e);
        em.getTransaction().commit();
    }
    
    public Object mergeEntity(Object e) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        Object t = em.merge(e);
        em.getTransaction().commit();
        return t;
    }
    
    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }
    
}
